class BillsController < ApplicationController
  def index
    @bills = Bill.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @bills }
    end
  end

  def show
    @bill = Bill.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @bill }
    end
  end

  def new
    @bill = Bill.new
    @bill.ref_id = Time.new.to_f.to_s
    @stocks = Stock.find(:all,:conditions => ['quantity>0'])
    respond_to do |format|
      format.html # new.html.erb
      format.json { render :json => @bill }
    end
  end

  def edit
    @bill = Bill.find(params[:id])
    @stocks = Stock.find(:all,:conditions => ['quantity>0'])
  end

  def create
    @stocks = Stock.find(:all,:conditions => ['quantity>0'])
    @bill = Bill.new(params[:bill])
    customer_id = @bill.customer_id
    electrician_id = @bill.electrician_id
    on_date = @bill.sold_date
    @bill.recompute_totals

    respond_to do |format|
      if @bill.save
        Transaction.create([:giver => Owner.find(1), :receiver => Customer.find(customer_id),:reference => @bill, :amount => @bill.grand_total, :on_date => on_date ])
        Transaction.create([:giver => Electrician.find(electrician_id), :receiver => Owner.find(1),:reference => @bill, :amount => @bill.total_commission, :on_date => on_date ])
        format.html { redirect_to @bill, notice: 'Bill was successfully created.' }
        format.json { render json: @bill, status: :created, location: @bill }
      else
        format.html { render action: "new" }
        format.json { render json: @bill.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    @bill = Bill.find(params[:id])

    respond_to do |format|
      if @bill.update_attributes(params[:bill])
        format.html { redirect_to @bill, notice: 'Bill was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @bill.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @bill = Bill.find_by_ref_id(params[:ref_id])
    if @bill.present? then @bill.destroy end
    Bill.delete_all_sold_items_from_bill(params[:ref_id])

    respond_to do |format|
      format.html { redirect_to bills_url }
      format.json { head :no_content }
    end
  end
end
